package org.grow.leavejpa.controller;

import org.grow.leavejpa.dao.UserInfoJpa;
import org.grow.leavejpa.entity.UserInfo;
import org.grow.leavejpa.entity.UserInfoDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 21-6-8
 */
@RestController
@RequestMapping("/regAbout")
public class RegController {

    @Autowired
    private UserInfoJpa userInfoJpa;
    @GetMapping("/usernameExits")
    public Boolean usernameExits(@RequestParam String username){
        UserInfo user = userInfoJpa.findByUsername(username);
        return user != null;
    }
@Autowired
private PasswordEncoder passwordEncoder;
    @PostMapping("/register")
    public Boolean register(@RequestBody UserInfoDto userInfoDto){

        UserInfo userInfo = new UserInfo();
//        userInfo.setUsername(userInfoDto.getUsername());
//        userInfo.setPassword(userInfoDto.getPassword());
//        userInfo.setNickname(userInfoDto.getNickname());
        BeanUtils.copyProperties(userInfoDto,userInfo);
        System.out.println(userInfo);
        userInfo.setUserId(0);
        userInfo.setIsEnable(true);
        userInfo.setLastLoginTime(LocalDateTime.now());
        System.out.println("加密前的密码："+userInfoDto.getPassword());
        String encode = passwordEncoder.encode(userInfoDto.getPassword());
        System.out.println("加密后的密码："+encode);
        userInfo.setPassword(encode);
        UserInfo info = userInfoJpa.findByUsername(userInfoDto.getUsername());
        if (info != null )return false;
        userInfoJpa.save(userInfo);
        return true;
    }
}
